<template>
	<view class="contract-details">
		<view class="paste">
			<uni-easyinput type="textarea" autoHeight v-model="templateText" placeholder="请输粘贴或输入文本，点击 “粘贴并识别” 自动识别"
				:maxlength="-1" />
			<view class="btns">
				<button type="primary" @click="copyTemplate" size="mini"
					style="margin-right: 20rpx;background-color: #409Eff">复制模板</button>
				<button type="primary" @click="pasteAndRecognize" size="mini"
					style="background-color: #409Eff;">粘贴并识别</button>
			</view>
		</view>

		<uni-section title="合同信息" type="line">
			<view class="form">
				<uni-forms ref="valiForm" :modelValue="dataForm" label-position="top" :rules="rules">
					<uni-forms-item :label="item.componentName" :name="item.componentType" :label-width="300" required
						v-for="(item, index) in dataForm.components" :key="item.componentId">

						<uni-easyinput v-if="item.componentType != '11'"
							v-model="dataForm.components[index].componentValue"
							:placeholder="`请输入${item.componentName}`" @blur="inputItem(_, item)" />



						<up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="3" v-else
							:maxCount="1" :previewFullImage="true"></up-upload>


					</uni-forms-item>
				</uni-forms>
				<button type="primary" @click="submit('valiForm')" style="background-color:#409Eff">提交</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
import {
	getContratDetails,
	uploadFile,
	setTemplateDC,
	addTemplateDC,
	getPersonalTemplateList
} from '@/api/app.js'
import {
	numberToChinese,
	getCurrentTime
} from '@/utils/index.js'
export default {
	data() {
		return {
			fileList: [],
			templateText: '',
			title: '',
			dataForm: {
				components: [],
				docTemplateId: '',
				docTemplateName: '',
				fileDownloadUrl: '',
				fileId: '',
				fileName: '',
				signFlowDescription: '',
				signFlowId: '',
				signFlowStatus: '',
				updateTime: '',

			},
			id: '',
			info: {},
			rules: {},
			selectedFile: '',
			customerName: '',
			phone: '',
			userId: '',
			userTemplete: []
		}
	},
	async onLoad(opt) {
		console.log(opt);
		if (opt) {
			this.userId = uni.getStorageSync('id')
			await this.getPersonalTemplateList()
			const title = decodeURIComponent(opt.title)
			this.title = title
			uni.setNavigationBarTitle({
				title
			})
			this.id = opt.id
			await this.getContratDetails(opt.id)
			this.dataForm.docTemplateId = opt.id
		}
	},
	methods: {
		// 获取模板标签
		async getPersonalTemplateList() {
			const res = await getPersonalTemplateList({
				id: this.userId
			})

			this.userTemplete = res.data
		},
		async afterRead(file) {
			console.log('file', file)
			const files = file.file
			console.log('files', files)
			this.fileList = [{
				url: files.url,
				type: files.type
			}]
			// 显示加载提示
			uni.showLoading({
				title: '上传中...',
				mask: true
			})

			uni.uploadFile({
				url: 'https://api.weijiashangejiance.com/api/EQB/UploadFile', //仅为示例，非真实的接口地址
				filePath: files.url,
				name: 'file',
				formData: {
					user: 'test'
				},
				success: (uploadFileRes) => {
					const resp = JSON.parse(uploadFileRes.data)
					if (resp.data) {
						this.dataForm.components.forEach(item => {
							if (item.componentType == "11") {
								item.componentValue = resp.data.fileId;
							}
						})
					}
					uni.hideLoading()
				},
				fail: (err) => {
					uni.hideLoading()
				}
			})
		},
		inputItem(value, item) {
			console.log(item);
			if (item.componentName.includes('客户提车时间：精准到年月日')) {
				const endTime = this.addYearsToChineseDate(item.componentValue, 3)
				console.log(endTime);

				this.dataForm.components.forEach(item => {
					if (item.componentName.includes('到期时间')) {
						item.componentValue = endTime
					}
				})
			}
		},
		addYearsToChineseDate(dateString, yearsToAdd) {
			console.log('收到', dateString, yearsToAdd);
			// 解析中文日期字符串
			const match = dateString.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);

			if (!match) {
				throw new Error('日期格式不正确，请使用 "YYYY年M月D日" 格式');
			}

			// 提取年、月、日（月份需要减1，因为Date中月份从0开始）
			const year = parseInt(match[1]);
			const month = parseInt(match[2]) - 1; // 重要：月份减1
			const day = parseInt(match[3]);

			// 创建Date对象
			const date = new Date(year, month, day);

			// 添加3年
			date.setFullYear(date.getFullYear() + yearsToAdd);

			// 格式化为中文日期字符串
			const newYear = date.getFullYear();
			const newMonth = date.getMonth() + 1; // 月份加1
			const newDay = date.getDate();

			return `${newYear}年${newMonth}月${newDay}日`;
		},
		async handleFileSelect(e) {

		},
		// 提交
		submit(ref) {
			this.$refs[ref].validate().then(async res => {
				for (let s of this.dataForm.components) {
					if (!s.componentValue) {
						uni.showToast({
							title: `请输入${s.componentName}`,
							icon: 'none'
						})
						return
					}
				}
				let customerName = ''
				let vin = ''
				// 获取当前表单的客户名字和车辆vin码
				this.dataForm.components.forEach((item) => {
					if (item.componentName.includes('客户名字') || item.componentName.includes(
						'客户姓名')) {
						customerName = item.componentValue
						this.customerName = item.componentValue
					}
					if (item.componentName.includes('车架号')) {
						vin = item.componentValue
					}

				})

				// 设置合同名字
				const templateName = `${this.title}_${customerName}_${vin}`
				console.log('设置合同名字', templateName);

				this.dataForm.fileName = templateName
				this.dataForm.docTemplateName = templateName
				console.log(this.dataForm);
				const resp = await setTemplateDC(this.dataForm)
				console.log(resp);

				if (resp.code === 0) {
					await this.addOrde(resp.data.fileId, this.dataForm.fileName, resp.data
						.fileDownloadUrl);
				} else {
					uni.showModal({
						title: "出错了",
						content: resp.message,
					})
				}
			}).catch(err => {
				console.log('err', err);
			})
		},

		isBool(str) {
			return str.includes('个人章')
		},

		async addOrde(fileId, signFlowTitle, url) {
			let order = {
				fileId,
				fileUrl: url,
				title: this.dataForm.fileName,
				name: this.customerName,
				phone: this.phone,
				memberId: uni.getStorageSync('id'),
				pdfId: this.id
			};

			const res = await addTemplateDC(order)
			if (res.code === 1) {
				uni.showToast({
					title: '提交成功',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			}
		},


		// 获取详情
		async getContratDetails(docTemplateId) {
			const userName = uni.getStorageSync('name')
			const mobile = uni.getStorageSync('mobile')
			const userRole = uni.getStorageSync('qx')


			const res = await getContratDetails({
				docTemplateId
			})
			if (res.message === '成功') {
				let xsList = res.data.components
				this.dataForm.components = xsList.map((item) => {
					return {
						componentId: item.componentId,
						componentType: item.componentType,
						componentName: item.componentName,
						componentValue: item.componentType === '11' ? [] : '',
					}
				})

				this.dataForm.components = this.dataForm.components.filter((item) => {
					return item.componentType !== '6';
				})

				this.info = res.data
			}

		},
		// 复制模板
		copyTemplate() {
			// 把模板数据复制到剪贴板 每一个需要一个换行符
			const template = this.dataForm.components.map(item => {
				return `${item.componentName}`
			}).join('\n')

			uni.setClipboardData({
				data: template,
				success() {
					uni.showToast({
						title: '复制成功',
						icon: 'none'
					})
				}
			})
		},
		// 粘贴识别
		pasteAndRecognize() {
			uni.getClipboardData({
				success: (res) => {
					this.templateText = res.data
					this.discernSalesContract(res.data)
				},
				fail(err) {
					console.log('err', err);
				}
			})
		},
		// 识别销售合同模板
		discernSalesContract(val) {
			// 使用正则表达式提取各字段
			const extractField = (fieldName) => {
				const regex = new RegExp(`${fieldName}：(.+)`);
				const match = val.match(regex);
				return match ? match[1].trim() : '';
			};
			const userCardNumber = this.userTemplete.find(item => item.name === '身份证号码')?.value
			const userName = uni.getStorageSync('name')
			const mobile = uni.getStorageSync('mobile')


		}
	}
}
</script>

<style scoped lang="scss">
.contract-details {
	padding: 20rpx 30rpx;
	min-height: 100vh;
	box-sizing: border-box;

	.paste {
		margin-bottom: 20rpx;
		padding: 20rpx;
		border-radius: 10rpx;
		background-color: #ffffff;

		.btns {
			padding-top: 20rpx;
			text-align: end;
		}
	}

	.form {
		margin-top: 20rpx;
		padding: 20rpx;
		border-radius: 10rpx;
		background-color: #ffffff;
	}
}
</style>